package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.thread.AppThreadLocalUtils;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    MongoTemplate mongoTemplate;

    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDTO dto) {
        ResponseResult<ApBehaviorEntry> responseResult = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), dto.getEquipmentId());
        if (responseResult.getCode()!=0){
            log.error("远程调用behaviorFeign.findByUserIdOrEquipmentId出错");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry behaviorEntry = responseResult.getData();
        if (behaviorEntry==null) {
            log.error("远程调用behaviorFeign.findByUserIdOrEquipmentId出错");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria.where("keyword").is(dto.getSearchWords()).and("entryId").is(behaviorEntry.getId())), ApUserSearch.class);
        if (apUserSearch == null){
            apUserSearch = new ApUserSearch();
            apUserSearch.setEntryId(behaviorEntry.getId());
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setKeyword(dto.getSearchWords());
        }else {
            apUserSearch.setCreatedTime(new Date());
        }
        mongoTemplate.save(apUserSearch);
        if (StringUtils.isNotBlank(dto.getSearchWords()) && dto.getSearchWords().length()>4){
            ApAssociateWords associateWords = mongoTemplate.findOne(Query.query(Criteria.where("associateWords").is(dto.getSearchWords())), ApAssociateWords.class);
            if (associateWords == null || StringUtils.isBlank(associateWords.getAssociateWords())){
                ApAssociateWords apAssociateWords = new ApAssociateWords();
                apAssociateWords.setAssociateWords(dto.getSearchWords());
                apAssociateWords.setCreatedTime(new Date());
                mongoTemplate.save(apAssociateWords);
            }
        }
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        if(dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorResult = behaviorFeign.findByUserIdOrEquipmentId(user==null?null:user.getId(), dto.getEquipmentId());
        if (behaviorResult.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,behaviorResult.getErrorMessage());
        }
        ApBehaviorEntry apBehaviorEntry = behaviorResult.getData();
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        dto.setPageSize(10);
        ApBehaviorEntry behaviorEntry = behaviorResult.getData();
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("createdTime").lt(dto.getMinBehotTime()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                .limit(dto.getPageSize()), ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        if (dto== null || dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        try {
            mongoTemplate.remove(Query.query(Criteria.where("id").is(dto.getId())),ApUserSearch.class);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("mongoDB删除历史记录出错，id为{}",dto.getId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        return ResponseResult.okResult();
    }
}
